package com.yonyou.marketing.app.api.service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.log4j.Logger;
import org.marketing.common.Response;
import org.marketing.common.AppAccessToken;
import org.marketing.common.constants.ExceptionMessage;
import org.marketing.common.dto.carOwner.CarOwnerDto;
import org.marketing.common.dto.customerInfo.CarInfoDto;
import org.marketing.common.dto.leads.InsuranceDto;
import org.marketing.common.event.BizEvent;
import org.marketing.common.event.enums.EventConstant.EventBizStep;
import org.marketing.common.exception.ServiceBizException;
import org.marketing.common.util.CheckUtil;
import org.marketing.common.util.CommonUtils;
import org.marketing.common.util.DateUtil;
import org.marketing.common.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.infoservice.filestore.FileStore;
import com.yonyou.gmmc.common.sms.SmsHttpClient2;
import com.yonyou.marketing.app.api.constant.AppConstant;
import com.yonyou.marketing.app.api.dao.TmAppLoginAccessTokenMapper;
import com.yonyou.marketing.app.api.dao.TmAppLoginuserInfoMapper;
import com.yonyou.marketing.app.api.dao.TmCarOwnerMapper;
import com.yonyou.marketing.app.api.dao.TmFeedbackMapper;
import com.yonyou.marketing.app.api.dao.TmPotentialUserMapper;
import com.yonyou.marketing.app.api.dao.TmPushBindingMapper;
import com.yonyou.marketing.app.api.dao.TmSmsLogMapper;
import com.yonyou.marketing.app.api.dto.CarInfoDTO;
import com.yonyou.marketing.app.api.model.AppData;
import com.yonyou.marketing.app.api.model.CarInfoPO;
import com.yonyou.marketing.app.api.model.TmAppLoginAccessToken;
import com.yonyou.marketing.app.api.model.TmAppLoginuserInfo;
import com.yonyou.marketing.app.api.model.TmCarOwner;
import com.yonyou.marketing.app.api.model.TmFeedback;
import com.yonyou.marketing.app.api.model.TmPotentialUser;
import com.yonyou.marketing.app.api.model.TmPushBinding;
import com.yonyou.marketing.app.api.model.TmSmsLog;
import com.yonyou.marketing.app.api.model.TtMessage;
import com.yonyou.marketing.app.api.model.UserDataDTO;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

@Service("appLoginService")
public class AppLoginService {

    private Logger                      logger        = Logger.getLogger(AppLoginService.class);
    @Value("${SMS-pass}")
    private String                      smsPass;
    @Value("${SMS-key}")
    private String                      smsKey;
    @Value("${SMS_CDKEY}")
    private String                      SMS_CDKEY;
    @Value("${SMS_PASS}")
    private String                      SMS_PASS;
    @Value("${SMS_BASEURL}")
    private String                      SMS_BASEURL;
    @Value("${SMS_TEMPLATEID_CARAPP}")
    private String                   	SMS_TEMPLATEID_CARAPP;

    @Autowired
    private TmSmsLogMapper              tmSmsLogMapper;
    @Autowired
    private TmCarOwnerMapper            tmCarOwnerMapper;
    @Autowired
    private TmPotentialUserMapper       tmPotentialUserMapper;
    @Autowired
    private TmPushBindingMapper         tmPushBindingMapper;
    @Autowired
    private TmAppLoginuserInfoMapper    tmAppLoginuserInfoMapper;
    @Autowired
    private TmAppLoginAccessTokenMapper tmAppLoginAccessTokenMapper;
    @Autowired
    private CustomerServiceInterface    customerServiceInterface;
    @Autowired
    private WeChatPushServiceInterface    weChatPushServiceInterface;
    @Autowired
    private TmFeedbackMapper            tmFeedbackMapper;

    private static long                 yxtime        = 1000 * 60 * 3;                          // 验证频率
    private Long                        defaultExpire = 30 * 24 * 3600l * 1000;

    /**
     * 向手机发送验证码
     * 
     * @author lyq
     * @param phoneNumber 要发送的手机号
     * @param msgType 短信类型
     * @return
     */
    public void sendMsgCode(String phoneNumber, Short msgType) {
        // 发送短信
        logger.info("发送短信To：" + phoneNumber + "   短信类型：" + msgType);
        Example example = new Example(TmSmsLog.class);
        Criteria criteria = example.createCriteria();
        criteria.andEqualTo("sendTo", phoneNumber);
        criteria.andEqualTo("msgType", msgType);
        criteria.andCondition("(CREATE_DATE +(1/24/60) * 3) >=", new Date());
        example.setOrderByClause("CREATE_DATE DESC");
        List<TmSmsLog> smsList = tmSmsLogMapper.selectByExample(example);
        String checkCodeGen = "";
        boolean isSame = false;
        if (!CheckUtil.NullOrEmpty(smsList)) {
            isSame = true;
            checkCodeGen = smsList.get(0).getMsgContent();
        } else {
            checkCodeGen = CommonUtils.randomCode(4);
        }
        String msgStr = "";
        if (msgType == 1) {
            msgStr = "欢迎注册，";
        } else if (msgType == 2) {
            msgStr = "重置密码，";
        } else if (msgType == 3) {
            msgStr = "手机号验证，";
        } else if (msgType == 4) {
            msgStr = "手机号验证登录，";
        } else if (msgType == 5) {
            msgStr = "手机号快捷登录，";
        }
        String content = msgStr +","+ checkCodeGen;
        String s = SmsHttpClient2.sendSms(smsPass, smsKey, SMS_TEMPLATEID_CARAPP, phoneNumber, content);
        if (!isSame) {
            TmSmsLog messageLog = new TmSmsLog();
            messageLog.setMsgType(msgType);
            messageLog.setMsgContent(checkCodeGen);
            messageLog.setSendTo(phoneNumber);
            messageLog.setCreateDate(new Date());
            messageLog.setLastchecktime(new Date());// 用来判断恶意提交
            messageLog.setSnedResult(s);
            tmSmsLogMapper.insertSelective(messageLog);
        }
        logger.info("发送短信————End");
        logger.info("返回码————" + s);

    }

    /**
     * 校验手机号是否可注册
     * 
     * @author lyq
     * @param phoneNumber 要校验的手机号
     * @return
     */
    public void checkPhoneNumberValid(String phoneNumber, String checkCode, short msgType) throws Exception {
        if (CheckUtil.NullOrEmpty(phoneNumber)) {
            throw new ServiceBizException(ExceptionMessage.APP_USER_REG_FAIL_PHONE_NULL);
        }
        if (CheckUtil.NullOrEmpty(checkCode)) {
            throw new ServiceBizException(ExceptionMessage.APP_CHECKCODE_IS_NULL);
        }
        Example example = new Example(TmSmsLog.class);
        Criteria criteria = example.createCriteria();
        criteria.andEqualTo("sendTo", phoneNumber);
        criteria.andEqualTo("msgType", msgType);
        example.setOrderByClause("CREATE_DATE DESC");
        List<TmSmsLog> smsList = tmSmsLogMapper.selectByExample(example);
        if (!CheckUtil.NullOrEmpty(smsList)) {
            String sentCheckCode = smsList.get(0).getMsgContent();
            Date sentCreateDate = smsList.get(0).getCreateDate();
            Integer id = smsList.get(0).getId();
            BigDecimal errorCount = smsList.get(0).getErrorCount();

            // (校验码未过期||不校验校验码是否过期)&&校验码是否正确
            logger.info("===checkCode==========");
            logger.info(System.currentTimeMillis() - sentCreateDate.getTime());
            logger.info(checkCode.equals(sentCheckCode) + "===checkCode.equals(sentCheckCode)");

            TmSmsLog sms = new TmSmsLog();
            sms.setId(id);
            sms.setLastchecktime(new Date());
            tmSmsLogMapper.updateByPrimaryKeySelective(sms);

            // 判断错误次数
            if (errorCount.intValue() > 10) {
                logger.info("失败次数超过10次");
                throw new ServiceBizException(ExceptionMessage.APP_CHECKCODE_10ERROR);
            }

            if ((System.currentTimeMillis() - sentCreateDate.getTime() < yxtime) && checkCode.equals(sentCheckCode)) {
                return;
            }

            logger.info("记录验证码失败次数+1");
            TmSmsLog smsCount = new TmSmsLog();
            smsCount.setId(id);
            smsCount.setErrorCount(errorCount.add(new BigDecimal(1)));
            ;
            tmSmsLogMapper.updateByPrimaryKeySelective(smsCount);
        }
        if (msgType == AppConstant.SEND_MSG_1) {
            throw new ServiceBizException(ExceptionMessage.APP_USER_REG_FAIL_CHECKCODE_INCORRECT);
        } else if (msgType == AppConstant.SEND_MSG_4) {
            throw new ServiceBizException(ExceptionMessage.APP_CHECKCODE_ERROR);
        }

    }
    //校验OpenId是否存在
    public void checkOpenId(String openId){
    	TmPotentialUser ex = new TmPotentialUser();
    	ex.setDeviceOpenId(openId);
		List<TmPotentialUser> pList = tmPotentialUserMapper.select(ex);
		if(!CheckUtil.NullOrEmpty(pList)&&!pList.isEmpty()){
			openId = CommonUtils.randomOpenId();
			checkOpenId(openId);
		}
    }
    public void registerAppUser(String phoneNumber, String checkCode, String password) throws Exception {
        logger.debug("registerAppUser............");
        if (!checkPhoneExists(phoneNumber)) {
        	if (!CheckUtil.NullOrEmpty(password) && password.length() >= 8 && password.length() <= 16) {
            }else{
            	throw new ServiceBizException(ExceptionMessage.APP_USER_REG__FAIL_PASS_LENGTH_INVALID);
            }
            
            // 校验手机号是否可以注册
            checkPhoneNumberValid(phoneNumber, checkCode, AppConstant.SEND_MSG_1);
            // app微信伪关注
            String openId = CommonUtils.randomOpenId();
            checkOpenId(openId);
            registerAppPotentialUser(phoneNumber,openId,true);
            // app注册
            CarOwnerDto memberDto = new CarOwnerDto();
            memberDto.setUserName(phoneNumber);
            memberDto.setPhone(phoneNumber);
            memberDto.setIdentifyingCode(checkCode);
            memberDto.setPassword(MD5Util.MD5Encode(password));
            customerServiceInterface.insertCarOwner(memberDto, openId);
            return;
        }
        throw new ServiceBizException(ExceptionMessage.APP_USER_REG_FAIL_PHONE_EXISTS);
    }
    // app微信伪关注
    public void registerAppPotentialUser(String phoneNumber,String openId,boolean flag) {
		logger.debug("registerAppUser............");
		// app微信伪关注
		BizEvent event = new BizEvent();
		event.setEventBizStep(EventBizStep.WECHAT_USER_ATTENTION);
		Map<String, Object> map = new HashMap<>();
		map.put("DEVICEOPENID", openId);
		map.put("SOURCETYPE", AppConstant.SOURCE_TYPE_10011002);
		map.put("APPTYPE", AppConstant.APP_TYPE_10011002);
		map.put("CREATEDATE", System.currentTimeMillis());
		map.put("SUBSCRIBEDATE", System.currentTimeMillis());
		map.put("STATUS", AppConstant.WX_STATUS_10011001);
		map.put("NICKNAME", 1);
		map.put("SEX", 1);
		map.put("CITY", 1);
		map.put("PROVINCE", 1);
		map.put("COUNTRY", 1);
		map.put("HEADIMGURL", 1);
		event.setEventData(map);
		customerServiceInterface.event(event);
		// 把最新短信验证码更新到潜客表
		Example ex = new Example(TmPotentialUser.class);
		Criteria cr = ex.createCriteria();
		cr.andEqualTo("deviceOpenId", openId);
		TmPotentialUser pot = new TmPotentialUser();
		//flag 为false时从登录跳转过来的不需要注册验证码，跳过最新短信验证码更新
		if(flag){
			// 获取最新短信验证码
			Example example = new Example(TmSmsLog.class);
			Criteria criteria = example.createCriteria();
			criteria.andEqualTo("sendTo", phoneNumber);
			criteria.andEqualTo("msgType", AppConstant.SEND_MSG_1);
			example.setOrderByClause("CREATE_DATE DESC");
			List<TmSmsLog> smsList = tmSmsLogMapper.selectByExample(example);
			pot.setIdentifyingCode(smsList.get(0).getMsgContent());
		}
		pot.setRegisterPhone(phoneNumber);
		pot.setIdentifyingCodeDate(new Date());
		tmPotentialUserMapper.updateByExampleSelective(pot, ex);
	}

    /**
     * App用户登录
     * 
     * @author lyq
     * @param phoneNumber 要校验的手机号
     * @return
     */
    public Map<String, Object> appUserLogin(Map<String, String> param) throws Exception {
        Map<String, Object> result = new HashMap<>();
        String phoneNumber = param.get("phone");
        String checkCode = param.get("msgCode");
        String password = param.get("password");
        if (!CheckUtil.NullOrEmpty(checkCode)) {
            checkPhoneNumberValid(phoneNumber, checkCode, AppConstant.SEND_MSG_5);
            Example example = new Example(TmSmsLog.class);
            Criteria criteria = example.createCriteria();
            criteria.andEqualTo("sendTo", phoneNumber);
            criteria.andEqualTo("msgContent", checkCode);
            criteria.andEqualTo("msgType", AppConstant.SEND_MSG_5);
            example.setOrderByClause("CREATE_DATE DESC");
            List<TmSmsLog> smsList = tmSmsLogMapper.selectByExample(example);
            if (!CheckUtil.NullOrEmpty(smsList)) {
                result = updateCarOwn(param);
            } else {
                throw new ServiceBizException(ExceptionMessage.APP_CHECKCODE_ERROR);
            }
        } else {
            TmCarOwner carOwner = new TmCarOwner();
            carOwner.setPhone(phoneNumber);
            TmCarOwner c = tmCarOwnerMapper.selectOne(carOwner);
            if (!CheckUtil.NullOrEmpty(c)) {
                String pw = c.getPassword();
                Short count = 0;
                if (!CheckUtil.NullOrEmpty(c.getCount())) {
                    count = c.getCount();
                }
                Date logTime = c.getLogTime();
                if (null == count || "null".equals(count)) {
                    result = updateCarOwn(param);
                }
                if (!pw.equals(MD5Util.MD5Encode(password))) {
                    if (null != logTime) {
                        if (count >= 5) {
                            throw new ServiceBizException(ExceptionMessage.APP_CHECKCODE_5ERROR);
                        }
                        if ((System.currentTimeMillis() - logTime.getTime()) < yxtime) {
                            Short count_ = (short) (count + 1);
                            updateCarOwner(phoneNumber, count_);
                            throw new ServiceBizException(ExceptionMessage.APP_USER_LOGIN_FAIL_PASSWORD_INCORRECT);
                        } else {
                            updateCarOwner(phoneNumber, (short) 0);
                            throw new ServiceBizException(ExceptionMessage.APP_USER_LOGIN_FAIL_PASSWORD_INCORRECT);
                        }
                    } else {
                        Short count_ = (short) (count + 1);
                        updateCarOwner(phoneNumber, count_);
                        throw new ServiceBizException(ExceptionMessage.APP_USER_LOGIN_FAIL_PASSWORD_INCORRECT);
                    }
                } else {
                    if (count >= 5) {
                        throw new ServiceBizException(ExceptionMessage.APP_CHECKCODE_5ERROR);
                    }
                    result = updateCarOwn(param);
                }
            }
        }
        return result;
    }

    public Map<String, Object> updateCarOwn(Map<String, String> param) throws Exception {
        Map<String, Object> result = new HashMap<>();
        String phone = param.get("phone");
        String msgCode = param.get("msgCode");
        String pword = param.get("password");
        String deviceId = param.get("deviceId");
        String deviceType = param.get("deviceType");
        String version = param.get("version");
        if (!checkPhoneExists(phone)) {
            throw new ServiceBizException(ExceptionMessage.APP_PHONE_NOT_EXISTS);
        } else {
            TmCarOwner carOwner = new TmCarOwner();
            carOwner.setPhone(phone);
            TmCarOwner user = tmCarOwnerMapper.selectOne(carOwner);

            if (!CheckUtil.NullOrEmpty(msgCode)) {// 验证码登陆
                // 登陆成功后, 登陆次数清0;
                updateCarOwner(phone, (short) 0);
            } else {
                // 密码登陆
                String password = user.getPassword();
                if (password.equals(MD5Util.MD5Encode(pword))) {
                    result.put("userId", user.getUserId());
                    result.put("userName", user.getUserName());
                    result.put("status", "0");
                }
            }
            // app微信伪关注
            String openId = CommonUtils.randomOpenId();
            checkOpenId(openId);
            Integer potentialId = tmCarOwnerMapper.selectCountByPhone(phone);
            if(potentialId==0){
            	registerAppPotentialUser(phone,openId,false);
            	TmPotentialUser tp = new TmPotentialUser();
            	tp.setDeviceOpenId(openId);
            	TmPotentialUser ppPo = tmPotentialUserMapper.selectOne(tp);
            	TmCarOwner tmCarOwner = new TmCarOwner();
            	tmCarOwner.setPhone(phone);
            	TmCarOwner ccPo = tmCarOwnerMapper.selectOne(tmCarOwner);
            	tmCarOwnerMapper.insertTrUserOwner(ccPo.getUserId(), ppPo.getPotentialUserId());
            }
            // 添加记录日志
            TmAppLoginuserInfo logInfo = new TmAppLoginuserInfo();
            logInfo.setUserId(user.getUserId());
            logInfo.setPhone(phone);
            logInfo.setDeviceId(deviceId);
            logInfo.setAppOsType(Short.valueOf(deviceType));
            logInfo.setAppVersion(version);
            logInfo.setLoginDate(new Date());
            logInfo.setCreateDate(new Date());
            logInfo.setCreateBy(0);
            int a = tmAppLoginuserInfoMapper.insertSelective(logInfo);
            logger.info("插入条数为：" + a);
            // 刷新Token
            AppAccessToken refreshAccessToken = refreshAccessToken(user);
            try {
                bindDevice(deviceId, user.getUserId(), phone, Integer.valueOf(deviceType));
            } catch (Throwable t) {
                logger.warn("绑定bindDevice失败，原因 ： " + t.getMessage(), t);
            }
            result.put("accessToken", refreshAccessToken);
            result.put("userId", user.getUserId());
            result.put("userName", user.getUserName());
            if (!CheckUtil.NullOrEmpty(user.getSex())) {
                result.put("sex ", user.getSex());
            } else {
                result.put("sex ", "");
            }
            return result;
        }
    }

    public void updateCarOwner(String phone, Short count_) throws Exception {
        Example ex = new Example(TmCarOwner.class);
        Criteria cr = ex.createCriteria();
        cr.andEqualTo("phone", phone);
        TmCarOwner ca = new TmCarOwner();
        ca.setLogTime(new Date());
        ca.setCount(count_);
        int a = tmCarOwnerMapper.updateByExampleSelective(ca, ex);
        logger.info("更新条数为：" + a);
    }

    public void bindDevice(String deviceId, Integer userId, String phone, Integer deviceType) throws Exception {
        // 删除设备及用户绑定关系
        // 重新绑定
        TmPushBinding pb = new TmPushBinding();
        pb.setDeviceId(deviceId);
        pb.setPhone(phone);
        int singleSelect = tmPushBindingMapper.selectCount(pb);
        logger.info("查询条数为：" + singleSelect);
        if (CheckUtil.NullOrEmpty(deviceId)) {
            if (singleSelect > 0) {
                int a = tmPushBindingMapper.delete(pb);
                logger.info("删除条数为：" + a);
            }
            deviceId = "null" + System.currentTimeMillis();
            TmPushBinding pushBinding = new TmPushBinding();
            pushBinding.setDeviceId(deviceId);
            pushBinding.setBindStatus((short) 1);
            pushBinding.setPhone(phone);
            pushBinding.setUserId(userId);
            int b = tmPushBindingMapper.insertSelective(pushBinding);
            logger.info("插入条数为：" + b);
        }

    }

    public AppAccessToken refreshAccessToken(TmCarOwner user) {
        // 保存用户AccessToken
        // 默认过期时间为
        AppAccessToken accessToken = new AppAccessToken();
        accessToken.setAccessToken(UUID.randomUUID().toString().replace("-", ""));
        accessToken.setExpire(defaultExpire);

        TmAppLoginAccessToken token = new TmAppLoginAccessToken();
        token.setUserId(user.getUserId());
        int a = tmAppLoginAccessTokenMapper.delete(token);
        logger.info("删除条数为：" + a);

        TmAppLoginAccessToken loginAccessToken = new TmAppLoginAccessToken();
        loginAccessToken.setUserId(user.getUserId());
        loginAccessToken.setAccessToken(accessToken.getAccessToken());
        loginAccessToken.setExpireDate(new Date(System.currentTimeMillis() + accessToken.getExpire()));
        int b = tmAppLoginAccessTokenMapper.insertSelective(loginAccessToken);
        logger.info("插入条数为：" + b);
        return accessToken;
    }

    /**
     * 忘记密码校验验证码
     * 
     * @author lyq
     * @param phoneNumber 要校验的手机号
     * @param checkCode 校验码
     * @return
     */
    public void forgetCheckCode(String phoneNumber, String checkCode) throws Exception {
        checkPhoneNumberValid(phoneNumber, checkCode, AppConstant.SEND_MSG_2);
    }

    /**
     * 忘记密码校验验证码
     * 
     * @author lyq
     * @param phoneNumber 要校验的手机号
     * @param checkCode 校验码
     * @return
     */
    public void resetPassword(String phoneNumber, String password) throws Exception {
        if (!CheckUtil.NullOrEmpty(password) && password.length() >= 8 && password.length() <= 16) {
            Example ex = new Example(TmCarOwner.class);
            Criteria cr = ex.createCriteria();
            cr.andEqualTo("phone", phoneNumber);
            TmCarOwner ca = new TmCarOwner();
            ca.setPassword(MD5Util.MD5Encode(password));
            ca.setCount((short) 0);
            tmCarOwnerMapper.updateByExampleSelective(ca, ex);
            return;
        }
        throw new ServiceBizException(ExceptionMessage.APP_USER_REG__FAIL_PASS_LENGTH_INVALID);
    }

    /**
     * 向手机发送快捷登录--验证码
     * 
     * @author lyq
     * @param phoneNumber 要校验的手机号
     * @return
     */
    public void sendPhoneMsgCodeMessage(String phoneNumber) throws Exception {
        if (checkPhoneExists(phoneNumber)) {
            sendMsgCode(phoneNumber, AppConstant.SEND_MSG_5);
            return;
        }
        throw new ServiceBizException(ExceptionMessage.APP_USER_REG_PHONE_NOT_EXISTS);
    }

    /**
     * 向手机发送重置密码验证码
     * 
     * @author lyq
     * @param phoneNumber 要校验的手机号
     * @return
     */
    public void sendPasswordForgetMessage(String phoneNumber) throws Exception {
        if (checkPhoneExists(phoneNumber)) {
            sendMsgCode(phoneNumber, AppConstant.SEND_MSG_2);
            return;
        }
        throw new ServiceBizException(ExceptionMessage.APP_USER_REG_PHONE_NOT_EXISTS);
    }

    /**
     * 二次验证使用的验证码
     * 
     * @author lyq
     * @param phoneNumber 要校验的手机号
     * @return
     */
    public void buyerTelCheckCode(String phoneNumber) throws Exception {
        sendMsgCode(phoneNumber, AppConstant.SEND_MSG_3);
    }

    /**
     * 向手机发送验证码
     * 
     * @author lyq
     * @param phoneNumber 要校验的手机号
     * @return
     */
    public boolean checkPhoneExists(String phoneNumber) {
        // 发送短信
        logger.info("=====check phone exists：" + phoneNumber);
        TmCarOwner car = new TmCarOwner();
        car.setPhone(phoneNumber);
        List<TmCarOwner> list = tmCarOwnerMapper.select(car);
        if (!CheckUtil.NullOrEmpty(list)) {
            return true;
        }
        return false;
    }

    /**
     * 手动绑定车辆
     * 
     * @author lyq
     * @param phoneNumber 要校验的手机号
     * @return
     */
    public Map<String, Object> bindCar(String phoneNumber, String vin, String engineNo) throws Exception {
    	if (!checkPhoneExists(phoneNumber)) {
    		throw new ServiceBizException(ExceptionMessage.APP_USER_REG_PHONE_NOT_EXISTS);
        }
        Integer userId = tmCarOwnerMapper.selectUserIdByPhone(phoneNumber);
        Map<String, Object> carInfoMap = new HashMap<>();
        CarInfoDTO dto = new CarInfoDTO();
        List<CarInfoDTO> l = new ArrayList<>();
        logger.info("=====userId：" + userId);
        CarInfoDto carInfo = new CarInfoDto();
        carInfo.setVin(vin);
        carInfo.setEngine(engineNo);
        Response<Map<String, Object>> result = customerServiceInterface.saveCarInfo(carInfo, userId.toString());
        if (!CheckUtil.NullOrEmpty(result)) {
            Integer code = result.getResultCode();
            if (code == 1) {
                Map<String, Object> resultMap = result.getData();
                String flag = resultMap.get("flag").toString();
                if (flag.equals("1")) {
                    String vins = resultMap.get("vin").toString();
                    List<CarInfoDTO> cid = tmCarOwnerMapper.selectCarInfo(vins);
                    if (cid != null) {
                    	dto.setDealerCode(cid.get(0).getDealerCode()==null?"":cid.get(0).getDealerCode());
                    	dto.setEngineNo(cid.get(0).getEngineNo()==null?"":cid.get(0).getEngineNo());
                    	dto.setModelCode(cid.get(0).getModelCode()==null?"":cid.get(0).getModelCode());
                    	dto.setOrderDate(cid.get(0).getOrderDate()==null?"":cid.get(0).getOrderDate());
                    	dto.setInsurer(cid.get(0).getInsurer()==null?"":cid.get(0).getInsurer());
                    	dto.setCarNumber(cid.get(0).getCarNumber()==null?"":cid.get(0).getCarNumber());
                    	dto.setInsuranceEffectiveDate(cid.get(0).getInsuranceEffectiveDate()==null?"":cid.get(0).getInsuranceEffectiveDate());
                    	dto.setInsuranceEndDate(cid.get(0).getInsuranceEndDate()==null?"":cid.get(0).getInsuranceEndDate());
                    	dto.setVehicleDate(cid.get(0).getVehicleDate()==null?"":cid.get(0).getVehicleDate());
                    	dto.setCarId(cid.get(0).getCarId()==null?"":cid.get(0).getCarId().toString());
                    	dto.setSaleDate(cid.get(0).getSaleDate()==null?"":cid.get(0).getSaleDate());
                    	dto.setVin(cid.get(0).getVin()==null?"":cid.get(0).getVin());
                    	
                    	dto.setBrandName(cid.get(0).getBrandName()==null?"":cid.get(0).getBrandName());
                    	dto.setCarName(cid.get(0).getCarName()==null?"":cid.get(0).getCarName());
                    	dto.setCarPic(cid.get(0).getCarPic()==null?"":cid.get(0).getCarPic());
                        
                        logger.info("返回车辆信息：" + dto);
                    }
                } else {
                    throw new ServiceBizException(ExceptionMessage.APP_CAR_INFO_NOT_EXISTS);
                }
            }
        }
        l.add(dto);
        carInfoMap.put("car", l);
        return carInfoMap;
    }

    public void deleteCarOwnerRelation(Integer userId, Integer carId) {
        if (CheckUtil.NullOrEmpty(userId)) {
            throw new ServiceBizException(ExceptionMessage.USERID_IS_NULL);
        }
        if (CheckUtil.NullOrEmpty(carId)) {
            throw new ServiceBizException(ExceptionMessage.APP_CAR_INFO_LIST);
        }
        logger.info("userId：" + userId + "   carId:"+carId);
        customerServiceInterface.updateCarinfoStu(carId.toString(), userId.toString());
    }

    public void modifyCarinfo(Map<String, Object> parmToMap) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        CarInfoDto paramDto = new CarInfoDto();
        String userId = parmToMap.get("userId").toString();
        String carId = parmToMap.get("carId").toString();
        if (CheckUtil.NullOrEmpty(userId)) {
            throw new ServiceBizException(ExceptionMessage.USERID_IS_NULL);
        }
        if (CheckUtil.NullOrEmpty(carId)) {
            throw new ServiceBizException(ExceptionMessage.APP_CAR_INFO_LIST);
        }
        if (!CheckUtil.NullOrEmpty(parmToMap.get("carNickname")) && !CheckUtil.NullOrEmpty(parmToMap.get("carNickname").toString())) {
        	paramDto.setCarNickname((String) parmToMap.get("carNickname"));
        }
        if (!CheckUtil.NullOrEmpty(parmToMap.get("carNumber")) && !CheckUtil.NullOrEmpty(parmToMap.get("carNumber").toString())) {
        	paramDto.setLicenseNo((String) parmToMap.get("carNumber"));
        }
        if (!CheckUtil.NullOrEmpty(parmToMap.get("insurer"))&& !CheckUtil.NullOrEmpty(parmToMap.get("insurer").toString())) {
        	paramDto.setInsurer((String) parmToMap.get("insurer"));
        }
        if (!CheckUtil.NullOrEmpty(parmToMap.get("vehicleDate")) && !CheckUtil.NullOrEmpty(parmToMap.get("vehicleDate").toString())) {
            paramDto.setVehicleDate(DateUtil.parseDate((String) parmToMap.get("vehicleDate"), "yyyy/MM/dd"));
        }
        if (!CheckUtil.NullOrEmpty(parmToMap.get("insuranceEffectiveDate"))&& !CheckUtil.NullOrEmpty(parmToMap.get("insuranceEffectiveDate").toString())) {
            paramDto.setInsuranceStartDate(DateUtil.parseDate((String) parmToMap.get("insuranceEffectiveDate"),
                                                              "yyyy/MM/dd"));
        }
        if (!CheckUtil.NullOrEmpty(parmToMap.get("vin"))&& !CheckUtil.NullOrEmpty(parmToMap.get("vin").toString())) {
        	paramDto.setVin((String) parmToMap.get("vin"));
        }
        paramDto.setCarId(Long.valueOf(carId));
        paramDto.setUserId(userId);
        resultMap = customerServiceInterface.updateCarinfo(paramDto);
        String errorCode = resultMap.get("errorCode").toString();
        if (errorCode.equals("0")) {
            logger.info("修改车辆信息成功");
            return;
        } else {
            throw new ServiceBizException(ExceptionMessage.APP_UPDATE_CAR_INFO_FAIL);
        }
    }

    public List<InsuranceDto> loadInsuranceCompanyInfo() {
        List<InsuranceDto> list = new ArrayList<InsuranceDto>();
        list = customerServiceInterface.getInsuranceMap();
        logger.info("查询到的结果数为：" + list.size());
        if (list.size() > 0) {
            return list;
        }
        throw new ServiceBizException(ExceptionMessage.APP_INSURANCE_INFO_LIST);
    }

    public Map<String, Object> loadCarinfoList(Integer userId, Integer carId) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<CarInfoPO> l = new ArrayList<>();
        if (CheckUtil.NullOrEmpty(userId)) {
            throw new ServiceBizException(ExceptionMessage.USERID_IS_NULL);
        } else {
            if (CheckUtil.NullOrEmpty(carId)) {
                logger.info("查询该用户所有车辆信息");
                l = tmCarOwnerMapper.selectCarInfoList(userId,null);
            } else {
                logger.info("查询制定ID的车辆信息");
                l = tmCarOwnerMapper.selectCarInfoList(userId, carId);
            }
        }
        map.put("carList", l);
        return map;
    }

    public AppData loadUserData(Integer userId) {
        AppData appData = new AppData();
        if (CheckUtil.NullOrEmpty(userId)) {
            throw new ServiceBizException(ExceptionMessage.USERID_IS_NULL);
        }
        List<Map<String, Object>> adInfo = new ArrayList<>();
        Map<String, Object> noc = new HashMap<>();
        List<UserDataDTO> sbfMap = new ArrayList<>();
        sbfMap = tmCarOwnerMapper.selectCarInfoByUserId(userId);
        logger.info("查询结果sbfMap为：" + sbfMap);
        for (UserDataDTO dto : sbfMap){
            noc.put("modelCodeNew", dto.getModelCodeNew()==null?"":dto.getModelCodeNew());
            noc.put("carId", dto.getCarId()==null?0:dto.getCarId());
            noc.put("vin", dto.getVin()==null?"":dto.getVin());
            noc.put("engine", dto.getEngine()==null?"":dto.getEngine());
            noc.put("licenseNo", dto.getLicenseNo()==null?"":dto.getLicenseNo());
            noc.put("picUrl", dto.getPicUrl()==null?"":dto.getPicUrl());
            noc.put("brandName", dto.getBrandName()==null?"":dto.getBrandName());
            noc.put("seriesName", dto.getSeriesName()==null?"":dto.getSeriesName());
            noc.put("carName", dto.getCarName()==null?"":dto.getCarName());
            noc.put("modelName", dto.getModelName()==null?"":dto.getModelName());
            noc.put("status", "正在维修...");
            adInfo.add(noc);
        }
        logger.info("查询结果noc为：" + noc);
        appData.getRows().addAll(adInfo);

        appData.setTotal(Long.valueOf(appData.getRows().size()));
        return appData;
    }
    
    public AppData getCarOwnerInfo(String userId){
        AppData appData = new AppData();
        if(CheckUtil.NullOrEmpty(userId)){
            throw new ServiceBizException(ExceptionMessage.USERID_IS_NULL);
        }
        List<com.yonyou.marketing.app.api.dto.CarOwnerDto> list = new ArrayList<>();
        list = tmCarOwnerMapper.selectUserInfo(userId);
        logger.info("查询出的车主信息数据有："+list.size()+"条");
        if(list.size()>0){
        	String count = tmCarOwnerMapper.countOwnerCar(userId);
            list.get(0).setCOUNTCAR(count);
            appData.getRows().addAll(list);
            appData.setTotal(Long.valueOf(appData.getRows().size()));
        }else{
        	appData.setRows(new ArrayList<Object>());
            appData.setTotal(0L);
        }
        return appData;
    }
    
    public void updateCarOwnerInfo(String userId,String username,Integer sex,String birthday,String address,String driverExpired) throws ParseException{
        TmCarOwner tmCarOwner = new TmCarOwner();
        if(CheckUtil.NullOrEmpty(userId)){
            throw new ServiceBizException(ExceptionMessage.USERID_IS_NULL);
        }
        if(!CheckUtil.NullOrEmpty(username)){
            tmCarOwner.setUserName(username);
        }
        if(!CheckUtil.NullOrEmpty(sex)){
            tmCarOwner.setSex(Short.valueOf(sex.toString()));
        }
        if(!CheckUtil.NullOrEmpty(birthday)){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            tmCarOwner.setBirthday(sdf.parse(birthday));
        }
        if(!CheckUtil.NullOrEmpty(address)){
            tmCarOwner.setAddress(address);
        }
        if(!CheckUtil.NullOrEmpty(driverExpired)){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            tmCarOwner.setDriverLicenseExpired(sdf.parse(driverExpired));
        }
        Example example = new Example(TmCarOwner.class);
        example.createCriteria().andCondition("USER_ID=", userId);
        int i = tmCarOwnerMapper.updateByExampleSelective(tmCarOwner, example);
        logger.info("更新了"+i+"条记录");
        if(i!=1){
            throw new ServiceBizException(ExceptionMessage.APP_UPDATA_CAR_OWNER_FAIL);
        }
    }
    
    public AppData feedbackInfo(String userId,String pageSize,String pageNo){
        AppData appData = new AppData();
        if(CheckUtil.NullOrEmpty(userId)){
            throw new ServiceBizException(ExceptionMessage.USERID_IS_NULL);
        }
        if(!CheckUtil.NullOrEmpty(pageSize)&&!CheckUtil.NullOrEmpty(pageNo)){
            PageHelper.startPage(Integer.parseInt(pageNo),Integer.parseInt(pageSize));
            List<TmFeedback> list = tmFeedbackMapper.feedbackInfo(userId);
            PageInfo<TmFeedback> page = new PageInfo<TmFeedback>(list);
            appData.getRows().add(page);
            appData.setTotal(Long.valueOf(appData.getRows().size()));
        }else{
            List<TmFeedback> list = tmFeedbackMapper.feedbackInfo(userId);
            appData.getRows().addAll(list);
            appData.setTotal(Long.valueOf(appData.getRows().size()));
        }
        return appData;
    }
    
    public AppData feedbackDetail(String feedbackId){
        AppData appData = new AppData();
        if(CheckUtil.NullOrEmpty(feedbackId)){
            throw new ServiceBizException(ExceptionMessage.APP_FEEDBACK_ID);
        }
        List<TmFeedback> list = tmFeedbackMapper.feedbackDetail(feedbackId);
        if(list.size()==0){
            throw new ServiceBizException(ExceptionMessage.APP_FEEDBACK_CONTENT);
        }
        appData.getRows().addAll(list);
        appData.setTotal(Long.valueOf(appData.getRows().size()));
        return appData;
    }
    
    public void saveFeedback(String userId,String content,String appVersion,String appOsType){
        if(CheckUtil.NullOrEmpty(userId)){
            throw new ServiceBizException(ExceptionMessage.USERID_IS_NULL);
        }
        TmFeedback tmFeedback = new TmFeedback();
        tmFeedback.setUserId(Integer.valueOf(userId));
        tmFeedback.setContent(content);
        if(!CheckUtil.NullOrEmpty(appVersion)){
            tmFeedback.setAppVersion(appVersion);
        }
        if(!CheckUtil.NullOrEmpty(appOsType)){
            tmFeedback.setAppOsType(Short.valueOf(appOsType));
        }
        int i = tmFeedbackMapper.insertSelective(tmFeedback);
        logger.info("新增了"+i+"条数据");
        if(i==0){
            throw new ServiceBizException(ExceptionMessage.APP_SAVE_FEEDBACK_ERROR);
        }
    }
    
    public void setHint(String userId,String hint_stat){
        if(CheckUtil.NullOrEmpty(userId)){
            throw new ServiceBizException(ExceptionMessage.USERID_IS_NULL);
        }
        TmCarOwner tmCarOwner = new TmCarOwner();
        tmCarOwner.setHintStat(Short.valueOf(hint_stat));
        Example example = new Example(TmCarOwner.class);
        example.createCriteria().andCondition("USER_ID=", userId);
        int i = tmCarOwnerMapper.updateByExampleSelective(tmCarOwner, example);
        logger.info("更新了"+i+"条记录");
        if(i==0){
            throw new ServiceBizException(ExceptionMessage.APP_SET_HINT_ERROR);
        }
    }
    
    public String getHint(String userId){
        String hint_stat = "";
        if(CheckUtil.NullOrEmpty(userId)){
            throw new ServiceBizException(ExceptionMessage.USERID_IS_NULL);
        }
        Example example = new Example(TmCarOwner.class);
        example.createCriteria().andCondition("USER_ID=", userId);
        List<TmCarOwner> list = tmCarOwnerMapper.selectByExample(example);
        logger.info("一共有"+list.size()+"条记录");
        if(list.size()==0){
            throw new ServiceBizException(ExceptionMessage.APP_USERINFO_SELECT_NOT);
        }
        if(CheckUtil.NullOrEmpty(list.get(0).getHintStat().toString())){
            throw new ServiceBizException(ExceptionMessage.APP_SET_HINT_NULL);
        }
        hint_stat = list.get(0).getHintStat().toString();
        return hint_stat;
    }
    
    public String setCarOwnerPhoto(String userId,MultipartFile imgFile){
        String fileUrl = "";
        if(CheckUtil.NullOrEmpty(userId)){
            throw new ServiceBizException(ExceptionMessage.USERID_IS_NULL);
        }
//        MultipartFile imgFile = (MultipartFile) ((MultipartHttpServletRequest) request).getFiles("photo");
        if(CheckUtil.NullOrEmpty(imgFile)){
            throw new ServiceBizException(ExceptionMessage.APP_SET_PHOTO_NULL);
        }
        // 获取上传文件的路径
        String uploadFilePath = imgFile.getOriginalFilename();
        logger.info("uploadFilePath:"+uploadFilePath);
        // 截取上传文件的文件名
        String uploadFileName = uploadFilePath
            .substring(uploadFilePath.lastIndexOf('\\') + 1,
                uploadFilePath.indexOf('.'));
        logger.info("uploadFileName:"+uploadFileName);
        // 截取上传文件的后缀
        String uploadFileSuffix = uploadFilePath.substring(
            uploadFilePath.indexOf('.') + 1, uploadFilePath.length());
        logger.info("uploadFileSuffix:"+uploadFileSuffix);
        //上传
        try{
            String imgName = FileStore.getInstance().write("nd02", "fs01", uploadFileName+"."+uploadFileSuffix,imgFile.getBytes());
            logger.info("图片名imgName:"+imgName);
            fileUrl = FileStore.getInstance().getDomainURL(imgName);
            logger.info("文件的上传地址为：");
            TmCarOwner records = new TmCarOwner();
            records.setIconsPhoto(fileUrl);
            Example example = new Example(TmCarOwner.class);
            example.createCriteria().andCondition("USER_ID=", userId);
            int i = tmCarOwnerMapper.updateByExampleSelective(records, example);
            logger.info("更新了"+i+"条数据");
            if(i==0){
                throw new ServiceBizException(ExceptionMessage.APP_SET_PHOTO_FAIL);
            }
        }catch(Exception e){
            logger.error(e.getMessage());
            throw new ServiceBizException(ExceptionMessage.APP_SET_PHOTO_FAIL);
        }
        return fileUrl;
    }
    
    /**
    * 校验APP的TOKEN是否有效
    * @author Administrator
    * @date 2018年1月29日
    * @param accessToken
    * @param userId
    * @return
    * @throws Exception
    */
    public Boolean checkAccessTokenExpire(String accessToken,String userId) throws Exception {
        try{
            Example example = new Example(TmAppLoginAccessToken.class);
            example.createCriteria().andCondition("ACCESS_TOKEN=", accessToken).andCondition("USER_ID=", userId);
            List<TmAppLoginAccessToken> list = tmAppLoginAccessTokenMapper.selectByExample(example);
            if(list.size()==0){
                logger.info("没有该用户的token");
                return false;
            }else{
                if(!list.get(0).getAccessToken().equals(accessToken) || list.get(0).getExpireDate().compareTo(new Date())<0){
                    logger.info("token不在有效期");
                    return false;
                }else{
                    return true;
                }
            }
        }catch(Exception e){
            logger.error(e.getMessage());
            throw new ServiceBizException(ExceptionMessage.APP_ACCESS_TOKEN_INVALID);
        }
    }
    public List<TtMessage> messageList(String userId){
        if(CheckUtil.NullOrEmpty(userId)){
            throw new ServiceBizException(ExceptionMessage.USERID_IS_NULL);
        }
        Response<List<TtMessage>> cList = weChatPushServiceInterface.messageList(userId);
        if(cList!=null && cList.getResultCode()==1){
        	return cList.getData();
		}else if(cList!=null && cList.getResultCode()==0){
			throw new ServiceBizException(cList.getErrMsg());
		}else{
			throw new ServiceBizException("消息服务异常");
		}
    }
    public List<TtMessage> message(String id){
        if(CheckUtil.NullOrEmpty(id)){
            throw new ServiceBizException(ExceptionMessage.APP_ACTIVITY_GROUP_CODE_IS_NULL);
        }
        Response<List<TtMessage>> cList = weChatPushServiceInterface.message(id);
        if(cList!=null && cList.getResultCode()==1){
        	return cList.getData();
		}else if(cList!=null && cList.getResultCode()==0){
			throw new ServiceBizException(cList.getErrMsg());
		}else{
			throw new ServiceBizException("消息服务异常");
		}
    }
    public Map<String, Object> readingFlag(String id){
        if(CheckUtil.NullOrEmpty(id)){
            throw new ServiceBizException(ExceptionMessage.APP_ACTIVITY_GROUP_CODE_IS_NULL);
        }
        Response<Map<String, Object>> cList = weChatPushServiceInterface.readingFlag(id);
        if(cList!=null && cList.getResultCode()==1){
        	return cList.getData();
		}else if(cList!=null && cList.getResultCode()==0){
			throw new ServiceBizException(cList.getErrMsg());
		}else{
			throw new ServiceBizException("消息服务异常");
		}
    }
    public Integer messageCount(String userId){
        if(CheckUtil.NullOrEmpty(userId)){
            throw new ServiceBizException(ExceptionMessage.USERID_IS_NULL);
        }
        Response<Integer> cList = weChatPushServiceInterface.messageCount(userId);
        if(cList!=null && cList.getResultCode()==1){
        	return cList.getData();
		}else if(cList!=null && cList.getResultCode()==0){
			throw new ServiceBizException(cList.getErrMsg());
		}else{
			throw new ServiceBizException("消息服务异常");
		}
    }
}
